package game

import (
	"base"
	. "gate_server/logic/internal"
	"gate_server/logic/player/api"
	"gate_server/model"
	"leaf/gate"
	"proto/player"
	"proto/server/gate"
)

type gameService struct {
}

func init() {
	service := new(gameService)

	Protocol.Register(new(proto_server_gate.Register), service.register)
	Protocol.Register(new(proto_server_gate.Response), service.response)
}

func (*gameService) register(args []interface{}) {
	msg := args[0].(*proto_server_gate.Register)
	base.Logger.Debug("game service register, %s", msg)

	agent := args[1].(gate.Agent)
	server := agent.UserData().(*model.GameServer)
	agentId := base.AgentId(msg.AgentId)
	if _, exists := system.servers[agentId]; exists {
		base.Logger.Error("game service register error, agent id %d is exists", agentId)
		agent.Close()
		return
	}

	server.SetId(agentId)
	system.servers[agentId] = server
}

func (*gameService) response(args []interface{}) {
	base.Logger.Debug("game service response")

	msg := args[0].(*proto_server_gate.Response)
	agent := args[1].(gate.Agent)

	server := agent.UserData().(*model.GameServer)
	agentId := server.Id()
	if _, exists := system.servers[agentId]; !exists {
		base.Logger.Error("game service response failed, agent id %d not exists", agentId)
		return
	}

	playerId := base.PlayerId(msg.PlayerId)
	player, exists := player_api.Get(playerId)
	if !exists {
		base.Logger.Release("game service response failed, player id %d not exists", playerId)
		return
	}

	client := player.Client()
	if client == nil {
		base.Logger.Release("game service response failed, player id %d client not exists", playerId)
		return
	}

	response := new(proto_player.Response)
	response.Name = msg.Name
	response.Data = msg.Data
	response.Code = msg.Code
	response.Args = msg.Args
	client.WriteMsg(response)
}
